import React from 'react'
import { Button, Divider, Icon, Input, Rate, Table, Tabs, Tag } from 'antd'
import Highlighter from 'react-highlight-words'
import _ from 'lodash'
import { FormattedMessage } from 'react-intl'
import { convertContent } from '../../../../../constant/lang-util'

const {TabPane} = Tabs

export default class AssignmentsSurveyQuizzesOverviewBox extends React.Component {
  state = {
    searchText: '',
    currentAssignmentId: -1
  }

  getColumnSearchProps = dataIndex => ({
    filterDropdown: ({setSelectedKeys, selectedKeys, confirm, clearFilters}) => (
      <div style={{padding: 8}}>
        <Input
          ref={node => {
            this.searchInput = node
          }}
          placeholder={`Search ${dataIndex}`}
          value={selectedKeys[0]}
          onChange={e => setSelectedKeys(e.target.value ? [e.target.value] : [])}
          onPressEnter={() => this.handleSearch(selectedKeys, confirm)}
          style={{width: 188, marginBottom: 8, display: 'block'}}
        />
        <Button
          type="primary"
          onClick={() => this.handleSearch(selectedKeys, confirm)}
          icon="search"
          size="small"
          style={{width: 90, marginRight: 8}}
        >
          Search
        </Button>
        <Button onClick={() => this.handleReset(clearFilters)} size="small" style={{width: 90}}>
          Reset
        </Button>
      </div>
    ),
    filterIcon: filtered => (
      <Icon type="search" style={{color: '#1890ff'}}/>
    ),
    onFilter: (value, record) => (record[dataIndex] || '')
      .toString()
      .toLowerCase()
      .includes(value.toLowerCase())
    ,
    onFilterDropdownVisibleChange: visible => {
      if (visible) {
        setTimeout(() => this.searchInput.select())
      }
    }
    ,
    render: text => (
      <Highlighter
        highlightStyle={{backgroundColor: '#ffc069', padding: 0}}
        searchWords={[this.state.searchText]}
        autoEscape
        textToHighlight={text.toString()}
      />
    ),
  })

  handleSearch = (selectedKeys, confirm) => {
    confirm()
    this.setState({searchText: selectedKeys[0]})
  }

  handleReset = clearFilters => {
    clearFilters()
    this.setState({searchText: ''})
  }

  formatTags = (item) => {
    if (!item) return ''

    const tagColors = item.split(',')

    return tagColors.map((item) => {
      const tagColor = item.split('|')
      return <Tag color={tagColor[1]}>{tagColor[0]}</Tag>
    })
  }
  getQuizLink = record => {
    const {programId} = this.props
    return `https://school.thoughtworks.cn/learn/program-center/surveyQuiz/index.html#/tutor/program/${programId}/task/${record.taskId}/student/${record.studentId}/divider/assignment/${record.assignmentId}/quiz/0`
  }

  getColumns = currentAssignmentId => {
    const {assignmentsSurveyQuizzesOverview} = this.props
    let quizzes = _.uniqBy(assignmentsSurveyQuizzesOverview.filter(item => item.assignmentId === currentAssignmentId),
      item => item.description)

    const colomns = [
      {
        title: <FormattedMessage id='姓名'/>,
        dataIndex: 'userName',
        width: 50,
        fixed:'left',
        key: 'name',
        render: (text, record) => {
          return <a target='_blank' href={this.getQuizLink(record)}>{text}</a>
        }
      }, {
        title: 'Tag',
        dataIndex: 'tag',
        fixed:'left',
        width: 80,
        ...this.getColumnSearchProps('tag'),
        render: (item) => {
          return <span>{this.formatTags(item)}</span>
        }
      }]
    quizzes.forEach(quiz => {
      colomns.push({
        title: quiz.description,
        width: 200,
        dataIndex: quiz.description,
        render: (text, record) => {
          const answer = record[text + 'answer']
          return answer
            ? <Rate style={{fontSize:15}} disabled defaultValue={parseInt(answer) + 1} count={record.choiceCount}/>
            : convertContent('未提交')
        }
      })
    })
    return colomns
  }

  getCurrentAssignment = currentAssignmentId => {
    const {assignmentsSurveyQuizzesOverview} = this.props
    let filterAssignments = assignmentsSurveyQuizzesOverview.filter(item => item.assignmentId === currentAssignmentId)
    let groupByUserAssignments = _.groupBy(filterAssignments, item => item.userName)
    return Object.keys(groupByUserAssignments).map(userName => {
      const currentUserAssignments = groupByUserAssignments[userName]
      const {tag, studentId, taskId, assignmentId} = currentUserAssignments[0]
      let result = {userName, studentId, tag, taskId, assignmentId}
      let groupByQuizzes = _.groupBy(currentUserAssignments, item => item.description)
      Object.keys(groupByQuizzes).forEach(description => {
        result[description] = description
        result[description + 'answer'] = groupByQuizzes[description][0].userAnswer
        result.choiceCount = new Set(groupByQuizzes[description]).length
      })

      return result
    })
  }

  render () {
    const {assignmentsSurveyQuizzesOverview} = this.props
    const {currentAssignmentId} = this.state
    const initAssignmentId = currentAssignmentId > 0
      ? currentAssignmentId
      : (assignmentsSurveyQuizzesOverview[0]||{}).assignmentId

    return <div>
      <Tabs tabPosition='left'
            onChange={currentAssignmentId => this.setState({currentAssignmentId:parseInt(currentAssignmentId)})}>
        {_.uniqBy(assignmentsSurveyQuizzesOverview, 'assignmentId').map((item) => {
          return <TabPane tab={<span>
          <span>
              <span style={{float: 'left'}}>{item.taskTitle}</span><br/>
              <span style={{fontSize: 12, fontWeight: 'lighter'}}>{item.assignmentTitle}</span>
          </span>
          <Divider type='vertical'/>
          <a onClick={() => this.props.getAssignmentsSurveyQuizzesStatus(item)}>{convertContent('详情')}</a>
        </span>} key={item.assignmentId}>
            {
              initAssignmentId === item.assignmentId
                ? <Table
                  columns={this.getColumns(item.assignmentId)}
                  dataSource={this.getCurrentAssignment(item.assignmentId)}
                  bordered
                  rowKey={item => item.studentId}
                  pagination={false}
                  scroll={{x: 'max-content'}}
                  size='small'
                />
                : ''
            }
          </TabPane>
        })}
      </Tabs>
    </div>

  }
}
